export const createStore = (createState) => {
  let state;
  let listeners = new Set();
  const getState = () => state;
  const setState = (fn) => {
    const nextState = typeof fn === 'function' ? fn(state) : fn;
    console.log('setState', nextState, state);
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state = Object.assign({}, previousState, nextState);
      //状态变更后依次调用监听函数
      listeners.forEach((listener) => listener(state, previousState));
    }
  }
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => {
      listeners.delete(listener);
    };
  };
  const api = {
    getState,
    setState,
    subscribe,
  }

  state = createState(setState, getState, api);
  console.log('createStore', state);
  return api;
};
export default createStore;
